<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\Score;
use App\Models\User;
use Illuminate\Http\Request;

class GameController extends Controller
{
    # 获取游戏列表数据
    public function getGame(){
        $result = Game::with('autor')->get();
        return view('game' , ['data' => $result]);
    }

    # 获取游戏详情页数据
    public function game($slug){
        $game = Game::where('slug' , $slug)
            ->with('autor')
            ->first();

        $users = User::select('id', 'username')->get();

        $score = [];
        foreach ($users as $user){
            $userScore = Score::where('game_id', $game->id)
                ->where('user_id', $user->id)
                ->orderby('score', 'desc')
                ->get();

            if ($userScore != null){
                $user['scores'] = $userScore;
                $score[] = $user;
            }
        }
        $game['score'] = $score;
//        return $game;
        return view('game_details' , ['data' => $game]);
    }

    private function ScoreDel($query , $forceDelete = false){
        if ($forceDelete){
            Score::where($query)->forceDelete();
            return;
        }
        Score::where($query)->delete();
    }

    # 删除游戏
    public function deleteGame(Request $request){
        $id = $request->only(['id']);
        Game::where($id)->update(['is_ban' => 1]);
        return redirect('Module_C/gameList');
    }

    # 删除所有分数
    public function deleteAllScore(Request $request){
        $id = $request->only(['id']);
        $this->ScoreDel(['game_id' => $id] , true);
        return redirect()->back();
    }

    # 删除某个用户某条分数
    public function deleteUserScore(Request $request){
        $id = $request->only(['id']);
        $this->ScoreDel($id);
        return redirect()->back();
    }

    #删除某个用户所有分数
    public function deleteUserAllScore(Request $request){
        $data = $request->only(['userId' , 'gameId']);
        $this->ScoreDel(['user_id' => $data['userId'] , 'game_id' => $data['gameId']]);
        return redirect()->back();
    }
}
